$(function () {
    const form = layui.form;
    const layer = layui.layer
    initCate();
    initEditor();

    function initCate() {
        $.ajax({
            type: 'GET',
            url: '/my/article/cates',
            success: function (res) {
                if (res.status !== 0) {
                    return layer.msg('初始化文章分类失败！')
                }
                // 调用模板引擎，渲染分类的下拉菜单
                var htmlStr = template('tpl-cate', res)
                $('[name=cate_id]').html(htmlStr)
                // 一定要记得调用 form.render() 方法
                form.render()
            }
        })
    }

    // 1. 初始化图片裁剪器
    const $image = $('#image')

    // 2. 裁剪选项
    const options = {
        aspectRatio: 400 / 280,
        preview: '.img-preview'
    }

    // 3. 初始化裁剪区域
    $image.cropper(options)

    $("#btnChooseImage").on("click", function () {
        $("#coverFile").click();
    })
    $("#coverFile").on("change", function (e) {
        const files = e.target.files;
        if (files.length === 0) {
            return layer.msg("请选择文件")
        }
        var newImgURL = URL.createObjectURL(files[0])
        $image
            .cropper('destroy')
            .attr('src', newImgURL)
            .cropper(options)
    })
    let pubState = "已发布";
    $("#draft").on("click", function () {
        pubState = "草稿";
    })
    $("#pub-form").on("submit", function (e) {
        e.preventDefault();
        const pubForm = new FormData($(this)[0]);
        pubForm.append("state", pubState);
        $image.cropper('getCroppedCanvas', {
            width: 400,
            height: 280
        }).toBlob(function (blob) {
            pubForm.append("cover_img", blob);
            publishArticle(pubForm)
        })
    })

    function publishArticle(fd) {
        $.ajax({
            type: "POST",
            url: "/my/article/add",
            data: fd,
            contentType: false,
            processData: false,
            success: function (res) {
                if (res.status !== 0) {
                    return layer.msg('发布文章失败！')
                }
                console.log('发布文章成功！');
                location.href = './article_list.html'
            }
        })
    }
})